package com.atguigu.guli.service.edu.controller.admin;

import com.atguigu.guli.common.base.result.R;
import com.atguigu.guli.common.base.result.ResultCodeEnum;
import com.atguigu.guli.common.base.util.ExceptionUtils;
import com.atguigu.guli.service.base.exception.GuliException;
import com.atguigu.guli.service.edu.entity.Subject;
import com.atguigu.guli.service.edu.service.SubjectService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author lj on 2021/1/26.
 * @version 1.0
 */

//@CrossOrigin
@Api(description = "课程类别管理")
@RestController
@RequestMapping("/admin/edu/subject")
@Slf4j
public class SubjectController {
    @Autowired
    private SubjectService subjectService;
    @ApiOperation(value = "Excel批量导入课程类别数据")
    @PostMapping("import")
    public R batchImport(
    @ApiParam(value = "Excel文件", required = true)
        @RequestParam("file") MultipartFile file) {
        try {
            InputStream inputStream = file.getInputStream();
            subjectService.batchImport(inputStream);
            return R.ok().message("批量导入成功");
        } catch (Exception e) {
            log.error(ExceptionUtils.getMessage(e));
            throw new GuliException(ResultCodeEnum.EXCEL_DATA_IMPORT_ERROR);
        }
    }

    @ApiOperation(value = "获取课程tree形图")
    @GetMapping("nested-list")
    public R getSubjectTree() {
       //获取父节点
        final List<Subject> parentSubjects = subjectService.list(new QueryWrapper<Subject>().eq("parent_id", "0"));
        if(CollectionUtils.isEmpty(parentSubjects)){
            return R.error().message("获取课程数据失败！");
        }
        final List<Subject> finalSubjects = parentSubjects.stream().map(parentSubject -> {
            //获取其子级
            final List<Subject> childrenSubjects = subjectService.list(new QueryWrapper<Subject>().eq("parent_id", parentSubject.getId()));

            return new Subject(parentSubject.getId(),parentSubject.getTitle(), childrenSubjects);
        }).collect(Collectors.toList());
        return R.ok().data("items",finalSubjects).message("获取课程数据成功!");
    }
}
